//
//  WJExtensionController.m
//  JerryIos
//
//  Created by jerrywang on 2018/2/9.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJExtensionController.h"
#import "WJCarBrand.h"
#import "WJCar.h"
#import "MJExtension.h"
#import "MJUser.h"
#import "MJStatus.h"
#import "MJStatusResult.h"
#import "MJAd.h"
#import "MJStudent.h"

@interface WJExtensionController() <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray *carBrandArray;

@end

@implementation WJExtensionController

- (NSArray *)carBrandArray {
    if (_carBrandArray == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"extension.plist" ofType:nil];
        NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *groupArray = [NSMutableArray array];
        for (NSDictionary *dic in dicArray) {
            WJCarBrand *carBrand = [WJCarBrand carBrandWithDict:dic];
            [groupArray addObject:carBrand];
        }
        _carBrandArray = groupArray;
    }
    return _carBrandArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建NavBar
    [self setupNavBar];
    // 创建tableView
    [self setupTableView];
}

// 创建NavBar
- (void)setupNavBar {
    //右边的按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"icon_share_normal"]
                                                                  highImage:[UIImage imageNamed:@"icon_share_selected"] target:self
                                                                     action:@selector(share)];
    //中间的标题
    self.navigationItem.title = @"MJExtension";
    
}

-(void)share{
    
}

// 创建tableView
- (void)setupTableView {
    
    //TableView的Frame
    CGFloat topHeight = [[UIApplication sharedApplication] statusBarFrame].size.height + 44;
    self.tableView.frame = CGRectMake(0, topHeight, self.view.bounds.size.width, self.view.bounds.size.height - topHeight);
    //指定代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.carBrandArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.carArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellId];
    }
    WJCarBrand *carBrand = self.carBrandArray[indexPath.section];
    WJCar *car = carBrand.carArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:car.icon];
    cell.textLabel.text = car.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:{
                    [self keyValues2object];
                    break;
                }
                case 1:{
                    [self keyValues2object1];
                    break;
                }
                case 2:{
                    [self keyValues2object2];
                    break;
                }
                case 3:{
                    [self keyValues2object3];
                    break;
                }
                case 4:{
                    [self keyValues2object4];
                    break;
                }
                case 5:{
                    [self keyValuesArray2objectArray];
                    break;
                }
                    
                default:
                    break;
            }
            break;
            
        case 1:
            switch (indexPath.row) {
                case 0:{
                    [self object2keyValues];
                    break;
                }
                case 1:{
                    [self object2keyValues2];
                    break;
                }
                case 2:{
                    [self objectArray2keyValuesArray];
                    break;
                }
                default:
                    break;
            }
            break;
            
        case 2:
            switch (indexPath.row) {
                case 0:{
                    [self coreData];
                    break;
                }
                default:
                    break;
            }
            break;
            
        default:
            break;
    }
}

/////////////////////////////////  字典/json --> 模型  ////////////////////////////////////////////
/**
 *  简单的字典 -> 模型
 */
- (void) keyValues2object {
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"name" : @"Jack",
                           @"icon" : @"lufy.png",
                           @"age" : @"20",
                           @"height" : @1.55,
                           @"money" : @"100.9",
                           @"sex" : @(SexFemale),
                           @"gay" : @"1"
                           //  @"gay" : @"NO"
                           //  @"gay" : @"true"
                           };
    
    // 2.将字典转为MJUser模型
    MJUser *user = [MJUser mj_objectWithKeyValues:dict];
    
    // 3.打印MJUser模型的属性
    [user description];
}

/**
 *  JSON字符串 -> 模型
 */
- (void) keyValues2object1 {
    // 1.定义一个JSON字符串
    NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20, \"height\":333333.7}";
    
    // 2.将JSON字符串转为MJUser模型
    MJUser *user = [MJUser mj_objectWithKeyValues:jsonString];
    
    // 3.打印MJUser模型的属性
    [user description];
}

/**
 *  复杂的字典 -> 模型 (模型里面包含了模型)
 */
-(void) keyValues2object2 {
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"text" : @"是啊，今天天气确实不错！",
                           
                           @"user" : @{
                                   @"name" : @"Jack",
                                   @"icon" : @"lufy.png"
                                   },
                           
                           @"retweetedStatus" : @{
                                   @"text" : @"今天天气真不错！",
                                   
                                   @"user" : @{
                                           @"name" : @"Rose",
                                           @"icon" : @"nami.png"
                                           }
                                   }
                           };
    
    // 2.将字典转为Status模型
    MJStatus *status = [MJStatus mj_objectWithKeyValues:dict];
    
    // 3.打印status的属性
    [status description];
}

/**
 *  复杂的字典 -> 模型 (模型的数组属性里面又装着模型)
 */
-(void) keyValues2object3 {
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"statuses" : @[
                                   @{
                                       @"text" : @"今天天气真不错！",

                                       @"user" : @{
                                               @"name" : @"Rose",
                                               @"icon" : @"nami.png"
                                               }
                                       },

                                   @{
                                       @"text" : @"明天去旅游了",

                                       @"user" : @{
                                               @"name" : @"Jack",
                                               @"icon" : @"lufy.png"
                                               }
                                       }

                                   ],

                           @"ads" : @[
                                   @{
                                       @"image" : @"ad01.png",
                                       @"url" : @"http://www.小码哥ad01.com"
                                       },
                                   @{
                                       @"image" : @"ad02.png",
                                       @"url" : @"http://www.小码哥ad02.com"
                                       }
                                   ],

                           @"totalNumber" : @"2014",
                           @"previousCursor" : @"13476589",
                           @"nextCursor" : @"13476599"
                           };

    // 2.将字典转为MJStatusResult模型
    MJStatusResult *result = [MJStatusResult mj_objectWithKeyValues:dict];

    // 3.打印MJStatusResult模型的属性
    [result description];
}

/**
 * 简单的字典 -> 模型（key替换，比如ID和id。多级映射，比如 oldName 和 name.oldName）
 */
-(void) keyValues2object4 {
    // 1.定义一个字典
    NSDictionary *dict = @{
                           @"id" : @"20",
                           @"desciption" : @"好孩子",
                           @"name" : @{
                                   @"newName" : @"lufy",
                                   @"oldName" : @"kitty",
                                   @"info" : @[
                                           @"test-data",
                                           @{@"nameChangedTime" : @"2013-08-07"}
                                           ]
                                   },
                           @"other" : @{
                                   @"bag" : @{
                                           @"name" : @"小书包",
                                           @"price" : @100.7
                                           }
                                   }
                           };

    // 2.将字典转为MJStudent模型
    MJStudent *stu = [MJStudent mj_objectWithKeyValues:dict];

    // 3.打印MJStudent模型的属性
    [stu description];
}

/**
 *  字典数组 -> 模型数组
 */
-(void) keyValuesArray2objectArray {
    // 1.定义一个字典数组
    NSArray *dictArray = @[
                           @{
                               @"name" : @"Jack",
                               @"icon" : @"lufy.png",
                               },

                           @{
                               @"name" : @"Rose",
                               @"icon" : @"nami.png",
                               }
                           ];

    // 2.将字典数组转为MJUser模型数组
    NSArray *userArray = [MJUser mj_objectArrayWithKeyValuesArray:dictArray];

    // 3.打印userArray数组中的MJUser模型属性
    for (MJUser *user in userArray) {
        [user description];
    }
}

/////////////////////////////////  模型 --> 字典/json  ////////////////////////////////////////////
/**
 *  模型 -> 字典
 */
-(void)object2keyValues {
    // 1.新建模型
    MJUser *user = [[MJUser alloc] init];
    user.name = @"Jack";
    user.icon = @"lufy.png";

    MJStatus *status = [[MJStatus alloc] init];
    status.user = user;
    status.text = @"今天的心情不错！";

    // 2.将模型转为字典
    NSDictionary *statusDict = status.mj_keyValues;
    
    MJExtensionLog(@"%@", statusDict);
    MJExtensionLog(@"%@", status.mj_JSONString);
    
    MJExtensionLog(@"%@", [status mj_keyValuesWithKeys:@[@"text"]]);
    
}

/**
 *  多级映射的模型 -> 字典
 */
-(void)object2keyValues2 {
    MJStudent *stu = [[MJStudent alloc] init];
    stu.ID = @"123";
    stu.oldName = @"rose";
    stu.nowName = @"jack";
    stu.desc = @"handsome";
    stu.nameChangedTime = @"2018-09-08";
    //book
    stu.books = @[@"Good book", @"Red book"];
    //bag
    MJBag *bag = [[MJBag alloc] init];
    bag.name = @"小书包";
    bag.price = 205;
    stu.bag = bag;
    
    NSDictionary *stuDict = stu.mj_keyValues;
    MJExtensionLog(@"%@", stuDict);
    MJExtensionLog(@"%@", stu.mj_JSONString);
    
    //忽略这以下key
    MJExtensionLog(@"%@", [stu mj_keyValuesWithIgnoredKeys:@[@"bag", @"oldName", @"nowName"]]);

    [MJStudent mj_referenceReplacedKeyWhenCreatingKeyValues:NO];
    MJExtensionLog(@"\n模型转字典时，字典的key参考replacedKeyFromPropertyName等方法:\n%@", stu.mj_keyValues);
}


/**
 *  模型数组 -> 字典数组
 */
-(void) objectArray2keyValuesArray {
    // 1.新建模型数组
    MJUser *user1 = [[MJUser alloc] init];
    user1.name = @"Jack";
    user1.icon = @"lufy.png";

    MJUser *user2 = [[MJUser alloc] init];
    user2.name = @"Rose";
    user2.icon = @"nami.png";

    NSArray *userArray = @[user1, user2];

    // 2.将模型数组转为字典数组
    NSArray *dictArray = [MJUser mj_keyValuesArrayWithObjectArray:userArray];
    MJExtensionLog(@"%@", dictArray);
    
}

/////////////////////////////////   字典 --> Core Data  ////////////////////////////////////////////
/**
 *  CoreData示例
 */
-(void) coreData {
    NSDictionary *dict = @{
                           @"name" : @"Jack",
                           @"icon" : @"lufy.png",
                           @"age" : @20,
                           @"height" : @1.55,
                           @"money" : @"100.9",
                           @"sex" : @(SexFemale),
                           @"gay" : @"true"
                           };
    
    // 这个Demo仅仅提供思路，具体的方法参数需要自己创建
    NSManagedObjectContext *context = nil;
    MJUser *user = [MJUser mj_objectWithKeyValues:dict context:context];
    
    // 利用CoreData保存模型
    [context save:nil];
    //print
    [user description];
}


@end
